<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="1200px"
    top="3vh"
    @close="close"
  >
    <el-form ref="formRef" :model="form" label-width="100">
      <el-row :gutter="15">
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>菜单权限设置</span>
              </div>
            </template>
            <div>
              <el-tree
                ref="eltreeRef"
                :default-checked-keys="form.RouteAuth"
                style="max-width: 600px"
                :data="routerList"
                show-checkbox
                node-key="id"
                default-expand-all
                check-strictly
                :props="defaultProps"
                @check="handleRouteAuth"
              />
            </div>
            <template #footer>
              <div style="height: 30px">
                <el-button
                  v-if="form.modRouteAuth"
                  type="primary"
                  size="small"
                  style="float: left"
                  @click="saveRouteAuth(0)"
                >
                  保存设置
                </el-button>
                <el-button
                  v-else
                  :type="isRouteAuth ? 'danger' : 'success'"
                  size="small"
                  style="float: left"
                  @click="saveRouteAuth(0)"
                >
                  保存设置
                </el-button>
                <el-button
                  v-if="permission == 2"
                  type="success"
                  size="small"
                  style="float: right"
                  @click="saveRouteAuth(1)"
                >
                  重置默认本岗位权限
                </el-button>
              </div>
            </template>
          </el-card>
        </el-col>
        <el-col :span="16">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>客户/业务权限</span>
              </div>
            </template>
            <el-form-item label="组织权限范围">
              <el-cascader
                v-model="form.CompanyID"
                :options="companyoptions"
                :props="companyProps"
                clearable
              />
            </el-form-item>
            <el-form-item label="业务类权限" prop="BusinessProducts">
              <el-cascader-panel
                v-model="form.BusinessProducts"
                style="width: fit-content; height: 350px"
                :props="{ multiple: true }"
                :options="optionsList"
              />
            </el-form-item>
            <!-- <el-form-item label="业务类权限">
              <el-checkbox
                v-model="checkAllBusinessClass"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllBusinessClassChange"
              >
                全部
              </el-checkbox>
              <el-checkbox-group
                v-model="checkedBusinessClass"
                @change="handleCheckedBusinessClassChange"
              >
                <el-checkbox
                  v-for="(item, index) in businessclassoptions"
                  :key="index"
                  :label="item.BusinessClassName"
                  :value="item.BusinessClassID"
                >
                  {{ item.BusinessClassName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="业务权限">
              <el-checkbox-group v-model="checkList">
                <el-checkbox label="查看" value="查看" />
                <el-checkbox label="修改" value="修改" />
              </el-checkbox-group>
            </el-form-item> -->
            <el-form-item label="负责行业" prop="Industrys">
              <el-transfer
                v-model="form.Industrys"
                :data="IndustryOptions"
                filterable
                filter-placeholder=""
                :titles="['选择行业', '已选']"
              />
            </el-form-item>
            <template #footer>
              <el-button type="primary" size="small" @click="saveUserIndustry">
                保存设置
              </el-button>
            </template>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>
<!-- :filter-method="filterMethod" -->
<script>
  import {
    getIndustrys,
    BusinessClassSelect,
    getStaffPostRouteAuth,
  } from '@/api/common'
  import {
    authRouterList,
    saveUserAuthRouter,
    saveStaffPostAuthRouter,
    saveUserIndustrys,
  } from '@/api/router'

  export default defineComponent({
    name: 'StaffAuthSet',
    props: {
      companyoptions: {
        type: Array,
        default: () => [],
      },
      businessclassoptions: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      console.log(
        'businessclassoptions',
        props.companyoptions,
        props.businessclassoptions
      )

      const state = reactive({
        isRouteAuth: true,
        optionsList: [],
        permission: 0,
        formRef: null,
        eltreeRef: null,
        form: {
          RouteAuth: [],
          Industrys: [],
        },
        title: '',
        dialogFormVisible: false,
        defaultProps: {
          children: 'children',
          label: 'label',
        },
        routerList: [],
        companyProps: {
          multiple: true,
          checkStrictly: true,
        },
        checkAllBusinessClass: false,
        isIndeterminate: true,
        checkedBusinessClass: [],
        IndustryOptions: [],
      })

      const handleCheckAllBusinessClassChange = (val) => {
        state.checkedBusinessClass = val ? props.businessclassoptions : []
        state.isIndeterminate = false
      }
      const handleCheckedBusinessClassChange = (value) => {
        const checkedCount = value.length
        state.checkAllBusinessClass =
          checkedCount === props.businessclassoptions.length
        state.isIndeterminate =
          checkedCount > 0 && checkedCount < props.businessclassoptions.length
      }
      // const filterMethod = (query, item) => {
      //   return item.initial.toLowerCase().includes(query.toLowerCase())
      // }
      // const handleRouteAuth = (checkedKeys, halfCheckedKeys) => {
      //   console.log('checkedKeys', checkedKeys)
      //   state.form.RouteAuth = halfCheckedKeys.checkedKeys
      // }

      const handleRouteAuth = (currentObj, treeStatus) => {
        // 用于：父子节点严格互不关联时，父节点勾选变化时通知子节点同步变化，实现单向关联。
        const selected = treeStatus.checkedKeys.indexOf(currentObj.id) // -1未选中,>=0为选中

        // 选中
        if (selected !== -1) {
          // 子节点只要被选中父节点就被选中(需要选中父节点时候调用此方法)
          selectedParent(currentObj)
          // 统一处理子节点为相同的勾选状态
          uniteChildSame(currentObj, true)
        } else {
          // 未选中 处理子节点全部未选中
          if (currentObj.children && currentObj.children.length !== 0) {
            uniteChildSame(currentObj, false)
          }
        }
      }

      const uniteChildSame = (treeList, isSelected) => {
        state['eltreeRef'].setChecked(treeList.id, isSelected)
        if (treeList.children) {
          for (let i = 0; i < treeList.children.length; i++) {
            uniteChildSame(treeList.children[i], isSelected)
          }
        }
      }

      const selectedParent = (currentObj) => {
        const currentNode = state['eltreeRef'].getNode(currentObj)
        if (currentNode.parent.key !== undefined) {
          state['eltreeRef'].setChecked(currentNode.parent, true)
          selectedParent(currentNode.parent)
        }
      }

      const getIndustry = async () => {
        const {
          data: { IndustryOptions },
        } = await getIndustrys()
        state.IndustryOptions = IndustryOptions
      }

      const saveUserIndustry = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await saveUserIndustrys(state.form)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }

      const saveRouteAuth = (savetype) => {
        const RouteAuth = state['eltreeRef'].getCheckedKeys()
        state.form.RouteAuth = RouteAuth
        state['formRef'].validate(async (valid) => {
          if (valid) {
            // saveStaffPostAuthRouter
            if (state.permission == 1) {
              console.log(state.form, '111')
              const { msg } = await saveStaffPostAuthRouter(state.form)
              $baseMessage(msg, 'success', 'vab-hey-message-success')
            }
            if (state.permission == 2) {
              console.log(state.form, '222')
              state.form.savetype = savetype
              const { msg } = await saveUserAuthRouter(state.form)
              $baseMessage(msg, 'success', 'vab-hey-message-success')
            }
            emit('fetch-data')
            close()
          }
        })
      }

      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          RouteAuth: [],
        }
        nextTick(() => {
          state['eltreeRef'].setCheckedKeys([])
        })
        state.dialogFormVisible = false
      }

      const showEdit = (row, type) => {
        getMsg()
        getIndustry()
        // state.permission  1是岗位的权限设置 2是员工的权限设置
        if (type == 'StaffPost') {
          state.permission = 1
        }
        if (type == 'User') {
          state.permission = 2
        }
        console.log(state.permission, type, 'state.permission')

        state.form = Object.assign({}, row)
        if (state.form.RouteAuth.length == 1 && state.form.RouteAuth[0] == 1) {
          state.isRouteAuth = true
          getStaffPostRoute()
        } else {
          state.isRouteAuth = false
        }

        // if (row.BusinessProducts.length != 0) {
        //   state.form.BusinessProducts = JSON.parse(row.BusinessProducts)
        // } else {
        //   state.form.BusinessProducts = []
        // }
        state.title = state.form.StaffName
        state.dialogFormVisible = true
      }

      const getAuthRouterList = async () => {
        state.listLoading = true
        const {
          data: { routerList },
        } = await authRouterList()
        state.routerList = routerList
        state.listLoading = false
      }

      onMounted(() => {
        getAuthRouterList()
      })
      const getStaffPostRoute = async () => {
        const dataMsg = {
          StaffPostID: state.form.StaffPostID,
        }
        const { data } = await getStaffPostRouteAuth(dataMsg)
        state.form.RouteAuth = data
        console.log(data, '222')
      }

      const getMsg = async () => {
        const {
          data: { BusinessClassOptions },
        } = await BusinessClassSelect()
        state.optionsList = BusinessClassOptions
        console.log('BusinessClassOptions', BusinessClassOptions)
      }

      return {
        ...toRefs(state),
        getMsg,
        getStaffPostRoute,
        handleCheckAllBusinessClassChange,
        handleCheckedBusinessClassChange,
        getAuthRouterList,
        showEdit,
        handleRouteAuth,
        saveRouteAuth,
        getIndustry,
        saveUserIndustry,
        // filterMethod,
        close,
      }
    },
  })
</script>
<style scoped>
  :deep(.el-scrollbar__wrap) {
    height: 350px;
  }
</style>
